#include "database.h"

database::database() {

    debug = 0;
    isConnected = 0;

    // pointer
    msgSystem = NULL;
    objManager = NULL;
    dbHandle = NULL;
}

void database::Init(string pHost, string pUser, string pPass, string pName) {

    DBhost = pHost;
    DBuser = pUser;
    DBpass = pPass;
    DBname = pName;

    int err;
    char Text[4000];

    // openDBX
    if( ( err = odbx_init( &dbHandle, "mysql", "127.0.0.1", "" ) ) < 0 ) {
        sprintf( Text, "odbx_init(): %s\n", odbx_error( dbHandle, err ) );
        if(debug) msgSystem->Add(Text);
    }

}

void database::IntroduceMessage(message *pMsgSystem) {
    msgSystem = pMsgSystem;
    if(debug) msgSystem->Add("sql: msgSystem linked");
}


void database::IntroduceObjManager(objectManager *pObjManager) {
    objManager = pObjManager;
    if(debug) msgSystem->Add("sql: objSystem linked");

}


void database::Connect(void) {

    int err;
    char Text[4000];

    // openDBX
    if( ( err = odbx_bind_simple( dbHandle, DBname.c_str(), DBuser.c_str(), DBpass.c_str() ) ) < 0 ) {
        sprintf( Text, "odbx_bind_simple(): %s\n", odbx_error( dbHandle, err ) );
        if(debug) msgSystem->Add(Text);
        isConnected = 0; // setRunning
    } else isConnected = 1; // TEMP down


}


void database::Trennen(void) {


    // openDBX
    odbx_finish( dbHandle );


    // setRunning
    isConnected = 0;

}





void database::InsertClassicLog(string message) {

    //logfile << "test:" << message << endl;


}


void database::InsertLog(int event_id, string message) {

    if(isConnected) {

        int err;
        char query[5000], Text[4000];
        sprintf(query,"INSERT INTO logs (event, message, event_time) VALUES ('%i','%s',FROM_UNIXTIME('%i') ); ", event_id, message.c_str(), (int)time(NULL) );
        if( ( err = odbx_query( dbHandle, query, strlen(query) ) ) < 0 ) {
            sprintf( Text, "odbx_query(): %s\n", odbx_error( dbHandle, err ) );
            if(debug) msgSystem->Add(Text);
        }

    }

}


//string database::sqlGetPlayerName(int pPlayerID) {

//    string retVal;

//    if(isConnected) {
/*
        database_ROW row;
        database_RES *res;

        char SQL[200] = "";
        sprintf(SQL, "SELECT name as result FROM svPlayer WHERE id = %i ", pPlayerID );

        if(database_query(sock, SQL )==0) {

            res = database_store_result(sock);                                         // Daten holen in Objekt
            while((row = database_fetch_row(res)) != NULL) {                           // Reihe grapschen
                retVal = row[0];
            }

            // Wichtig sonst SYNC Fehler
            database_free_result(res);

        }
        else {
            sprintf(SQL,"sqlCount: error: %s", database_error(sock));
            if(debug) msgSystem->Add(SQL);
        }
*/
//    }
//    return retVal;
//}




database::StructMsgShowCharacters database::getCharacters(int AccountID) {
    StructMsgShowCharacters retVal;


    return retVal;
}





int database::sqlCount(string pField, string pStatement) {

    int retVal=0;

    if(isConnected) {
/*
        // Trimming
        pField      = boost::trim_copy(pField);
        pStatement  = boost::trim_copy(pStatement);

        database_ROW row;
        database_RES *res;

        char SQL[200] = "";
        sprintf(SQL, "SELECT Count(*) as result FROM %s WHERE %s ", pField.c_str(), pStatement.c_str() );

        if(database_query(sock, SQL )==0) {

            res = database_store_result(sock);                                         // Daten holen in Objekt
            while((row = database_fetch_row(res)) != NULL) {                           // Reihe grapschen
                retVal = atoi(row[0]);
            }

            // Wichtig sonst SYNC Fehler
            database_free_result(res);

        }
        else {
            sprintf(SQL,"sqlCount: error: %s", database_error(sock));
            if(debug) msgSystem->Add(SQL);
        }

*/
    }

    return retVal;
}


int database::checkLoginGetUserID(string pUser, string pPass) {

    int retVal=-1;

    if(isConnected) {


        // Trimming
        pUser  = boost::trim_copy(pUser);
        pPass  = boost::trim_copy(pPass);

        int err;
        char query[5000], Text[4000];
        odbx_result_t* result;
        struct timeval tv = { 3, 0 };

        // MAKE QUERY
        sprintf(query, "SELECT * FROM login WHERE username = '%s' AND password = '%s' ", pUser.c_str(), pPass.c_str() );

        // SEND QUREY
        if( ( err = odbx_query( dbHandle, query, strlen(query) ) ) < 0 ) {
            sprintf( Text, "checkLogin: odbx_query(): %s\n", odbx_error( dbHandle, err ) );
            if(debug) msgSystem->Add(Text);
        }

        // GET RESULT
        while( ( err = odbx_result( dbHandle, &result, &tv, 0 ) ) != 0 ) {

            if( err < 0 ) msgSystem->Add("checkLogin: ERROR");

            while( ( err = odbx_row_fetch( result ) ) != 0 ) {

                if( err < 0 ) {
                    sprintf( Text, "checkLogin: odbx_row_fetch(): %s\n", odbx_error( dbHandle, err ) );
                    msgSystem->Add(Text);
                    break;
                }


                int i;
                for( i = 0; i < (int)odbx_column_count( result ); i++ ) {

                    // get the ID field
                    if(!strcmp(odbx_column_name( result, i ), "id")) {
                        retVal = atoi(odbx_field_value( result, i ));
                    }

                } //for i

            } // while fetch

            odbx_result_free(result);
            //tv = { 3, 0 };


        } // while FETCH


        return retVal;
    }
    return retVal;
}


int database::checkLogin(string name, string pass) {

    int retVal=-1;
    if(isConnected) {
        retVal = checkLoginGetUserID(name, pass);




    }

    return retVal;
}


void database::checkDatabase(bool pInit) {

    if(isConnected) {


        int err;
        char query[5000], Text[4000];
        odbx_result_t* result;
        struct timeval tv = { 3, 0 };

        // MAKE QUERY
        if(pInit) sprintf(query," SELECT objects.*, characters.login_id FROM objects, characters WHERE objects.status >= 1 AND characters.id = objects.character_id ");
        else sprintf(query,"SELECT * FROM objects WHERE status >= 1 AND changed = 1 ");

        // SEND QUREY
        if( ( err = odbx_query( dbHandle, query, strlen(query) ) ) < 0 ) {
            sprintf( Text, "sql-add: odbx_query(): %s\n", odbx_error( dbHandle, err ) );
            if(debug) msgSystem->Add(Text);
        }


        // GET RESULT
        while( ( err = odbx_result( dbHandle, &result, &tv, 0 ) ) != 0 ) {

            if( err < 0 ) {
                //sprintf( stderr, "odbx_result(): %s\n", odbx_error( dbHandle, err ) );
                msgSystem->Add("sql-add: ERROR");
            }


            // created needed stuff
            object tmpObjekt;



            // Fetch rows and process values
            while( ( err = odbx_row_fetch( result ) ) != 0 ) {

                if( err < 0 ) {
                    sprintf( Text, "sql-add: odbx_row_fetch(): %s\n", odbx_error( dbHandle, err ) );
                    msgSystem->Add(Text);
                    break;
                }


                int i;
                for( i = 0; i < (int)odbx_column_count( result ); i++ ) {

                    // ID
                    if(!strcmp(odbx_column_name( result, i ), "id")) {
                        tmpObjekt.id = atoi(odbx_field_value( result, i ));
                    }else

                    // character_id
                    if(!strcmp(odbx_column_name( result, i ), "character_id")) {
                        tmpObjekt.character_id = atoi(odbx_field_value( result, i ));
                    }else

                    // name
                    if(!strcmp(odbx_column_name( result, i ), "name")) {
                        tmpObjekt.name = odbx_field_value( result, i );
                    }else

                    // x
                    if(!strcmp(odbx_column_name( result, i ), "x")) {
                        tmpObjekt.x = atoi(odbx_field_value( result, i ));
                    }else

                    // y
                    if(!strcmp(odbx_column_name( result, i ), "y")) {
                        tmpObjekt.y = atoi(odbx_field_value( result, i ));
                    }else

                    // type
                    if(!strcmp(odbx_column_name( result, i ), "type")) {
                        tmpObjekt.type = atoi(odbx_field_value( result, i ));
                    }else

                    // status
                    if(!strcmp(odbx_column_name( result, i ), "status")) {
                        tmpObjekt.status = atoi(odbx_field_value( result, i ));
                    }else

                    // account_id
                    if(!strcmp(odbx_column_name( result, i ), "account_id")) {
                        tmpObjekt.account_id = atoi(odbx_field_value( result, i ));
                    }

                }

                // do stuff each object
                int ret;
                ret = objManager->AddObject(tmpObjekt);
                sprintf(Text,"sql-add: Load Object ID:  %i", (int)ret);
                if(debug) msgSystem->Add(Text);



            }

            odbx_result_free(result);
            //tv = { 3, 0 };


        } // while FETCH


    } else if(debug) msgSystem->Add("sql-add: checkdatabase NOT connected");

}
